package com.bafa.front.events;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bafa.dbcache.LeagueCache;
import com.bafa.debug.Debug;
import com.bafa.exceptions.ErrorException;
import com.bafa.exceptions.PasswordIsWrongException;
import com.bafa.exceptions.UserDoesNotExistException;
import com.bafa.front.utils.FrontUtils;
import com.bafa.objects.AdminUser;
import com.bafa.objects.PageBean;
import com.bafa.objects.User;
import com.bafa.services.LogonServices;
import com.bafa.services.RetrieveServices;

public class LogonEvent extends Event {

	@Override
	public void doEvent(HttpServletRequest request,
			HttpServletResponse response, PageBean page) {
		HttpSession session = request.getSession();
		User user = null;
		
		Debug.debug(this.getClass(),"doEvent","Entering......");
		try {
			if (FrontUtils.isLoggedOn(request)) {
				user = (User) FrontUtils.getUser(request);
			} else {
				if (request.getParameter("user") != null) {
					user = LogonServices.logon(request.getParameter("user"),
							request.getParameter("password"));
					session.setAttribute("LOGGEDON",user);
					if (request.getParameter("rememberme") != null
							&& request.getParameter("rememberme")
									.equalsIgnoreCase("true")) {
						FrontUtils.rememberMeCookie(response, request
								.getParameter("user"));
					}
				}
			}
			Debug.debug(this.getClass(),"doEvent","Found out if logged on");
			if (user instanceof AdminUser) {
				new AdminHomeEvent().doEvent(request, response, page);
			} else if (user.isResetPassword()) {
				new DisplayChangePasswordEvent().doEvent(request, response, page);
			} else {
				new UserHomeEvent().doEvent(request, response, page);
			}
			Debug.debug(this.getClass(),"doEvent","1. Page ID is: "+page.getId());
			session.setAttribute("LOGGEDON", user);

		} catch (UserDoesNotExistException userwrong) {
			message.addError("Use does not exist. Please check ");
			page.addDetails(RetrieveServices.getPage("logon"));
		} catch (PasswordIsWrongException passwordwrong) {
			message.addError("Password is wrong. Please try again ");
			page.addDetails(RetrieveServices.getPage("logon"));
		}
		Debug.debug(this.getClass(),"doEvent","....Leaving");
	}

}
